import {
  create,
  deleteById,
  findAlarmRules,
  findOne,
  modify,
  oneKeyAddMonitor,
  statusByPipelineId,
  statusByRule
} from '@/services/alarm-rule-api';
import {PauseCircleOutlined, PlayCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import {Button, Drawer, message, Modal, Space} from 'antd';
import React, {useRef, useState} from 'react';
import {enumInKey} from "@/utils/calculateUtil";
import moment from 'moment';
import {MonitorName} from "@/services/ant-design-pro/enums";
import CreateOrUpdateForm from "./components/CreateOrUpdateForm";
import {useLocation} from "@@/exports";

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.Channel) => {
  const hide = message.loading('正在添加');
  try {
    const res = await create({...fields});
    hide();
    if (res) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.Channel) => {
  const hide = message.loading('更新中');
  try {
    const res = await modify(fields);
    hide();

    if (res) {
      message.success('更新成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};



export type AlarmProps = {
  pipelineId?:number;
  wrapContainer?: boolean;
}


const AlarmRule: React.FC<AlarmProps> = (props) => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [createOrUpdateModalOpen, handleCreateOrUpdateModalOpen] = useState<boolean>(false);
  const [isCreate, handleIsCreate] = useState<boolean>(true);
  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.AlarmRule>();
  const wrapContainer : boolean = (props?.wrapContainer === undefined? true: props.wrapContainer );
  const location = useLocation();
  // @ts-ignore
  const pipelineId = props?.pipelineId || location?.state?.pipelineId || null;

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.Channel) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const res = await deleteById(selectedRows.id);
      hide();
      if (res) {
        message.success('删除成功');
        actionRef.current?.reload();
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };

  const changeStatus = async (status:string,pauseTime:string) => {
    const hide = message.loading('处理中....');
    try {
      const res = await statusByPipelineId({pipelineId:props?.pipelineId,status:status,pauseTime:pauseTime});
      hide();

      if (res) {
        message.success('操作成功');
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  }

  const changeStatusByRuleId = async (ruleId:any,status:string,pauseTime:string) => {
    const hide = message.loading('处理中....');
    try {
      const res = await statusByRule({alarmRuleIds:ruleId,status:status,pauseTime:pauseTime});
      hide();

      if (res) {
        message.success('操作成功');
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };

  const handleOneKeyAddMonitor = async () => {
    const hide = message.loading('添加中....');
    try {
      const res = await oneKeyAddMonitor(props?.pipelineId);
      hide();

      if (res) {
        message.success('添加成功');
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  }

  const columns: ProColumns<API.AlarmRule>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch:true
    },
    {
      title: '监控项目',
      dataIndex: 'monitorName',
      renderText: value => enumInKey(MonitorName, value),
    },
    {
      title: '阈值',
      dataIndex: 'matchValue',
      search: true,
      hideInForm: true,
    },
    {
      title: '状态',
      dataIndex: ['status'],
      sorter: true,
      search: false,
      hideInForm: true,
      renderText: (value, record) => (value === 'ENABLE' && !record?.isPause) ? '开启' : '暂停',
    },
    {
      title: '发送对象',
      dataIndex: ['receiverKey'],
      search: false,
      hideInTable: true
    },
    {
      title: '暂停时间',
      dataIndex: ['pauseTime'],
      search: false,
      hideInTable: true,
      renderText: (value, record) => value && record?.isPause ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (<>
          <Space>
            <a onClick={() => Modal.info({title: '描述', content: record?.description,maskClosable:true, footer: null})}>
              描述
            </a>
            <a
              type='button'
              key="edit"
              onClick={() => {
                handleIsCreate(false);
               return  handleUpdate(record);
              }}
            >编辑
            </a>

            {record?.status === 'ENABLE' && record?.isPause && (
              <a
                type='button'
                key="status"
                onClick={() => changeStatusByRuleId(record?.id,'enable',moment().format('YYYY-MM-DD HH:mm:ss'))}
              >恢复
              </a>
            )}

            {record?.status === 'ENABLE' && !record?.isPause && (
              <a
                type='button'
                key="pause"
                onClick={() =>  changeStatusByRuleId(record?.id,'disable',moment().format('YYYY-MM-DD HH:mm:ss'))}
              >暂停
              </a>
            )}

            {(record?.status !== 'ENABLE' || record?.isPause) && (
              <a
                type='button'
                key="delete"
                onClick={() => handleRemove(record)}
              >删除
              </a>
            )}
          </Space></>
      )

    }
  ];
  const toolBar = () => {

    const bars = (props?.pipelineId && (actionRef.current?.pageInfo?.total || -1) > 0 )? [
      <Button
        type="primary"
        key="primary"
        onClick={() => changeStatus('enable',moment().format('YYYY-MM-DD HH:mm:ss'))}
      >
        <PlayCircleOutlined /> 全部开启
      </Button>,
      <Button
        type="primary"
        key="primary"
        onClick={ () => changeStatus('disable',moment().format('YYYY-MM-DD HH:mm:ss'))}
      >
        <PauseCircleOutlined/> 全部暂停
      </Button>,
    ]:[]

    return props?.pipelineId? (
      [
        <Button
          type="primary"
          key="primary"
          onClick={() => {handleCreateOrUpdateModalOpen(true)}}
        >
          <PlusOutlined/> 新建
        </Button>,
        <Button
          type="primary"
          key="primary"
          onClick={() => handleOneKeyAddMonitor()}
        >
          <PlusOutlined/> 一键添加
        </Button>,
        ...bars
      ]
    ):[];
  }
  const AlarmRuleTale: React.FC = () => (<>
    <ProTable<API.AlarmRule, API.PipelinePageRequest>
      headerTitle='监控规则管理'
      actionRef={actionRef}
      rowKey="key"
      search={{
        labelWidth: 120
      }}
      toolBarRender={toolBar}
      request={findAlarmRules}
      columns={columns}
      params={{pipelineId:pipelineId}}
    />
    {props?.pipelineId &&
      <CreateOrUpdateForm
      onSubmit={async (value) => {
        let success;
        if (currentRow?.id) {
          success = await handleUpdate(value);
        } else {
          success = await handleAdd(value);
        }
        if (success) {
          handleCreateOrUpdateModalOpen(false);
          setCurrentRow(undefined);
          await actionRef?.current?.reload();
          return true;
        }
        return false;
      }}
      title={isCreate ? '新建' : '编辑'}
      onCancel={() => {
        handleCreateOrUpdateModalOpen(false);
        if (!showDetail) {
          setCurrentRow(undefined);
        }
      }}
      updateModalOpen={createOrUpdateModalOpen}
      values={currentRow}
    />}

    <Drawer
      width={500}
      open={showDetail}
      onClose={() => {
        setCurrentRow(undefined);
        setShowDetail(false);
      }}
      closable={false}
    >
      {currentRow?.id && (
        <ProDescriptions<API.AlarmRule>
          column={2}
          title={currentRow?.monitorName}
          request={async () => findOne(currentRow?.id)}
          params={{
            id: currentRow?.id,
          }}
          columns={columns as ProDescriptionsItemProps<API.AlarmRule>[]}
        />
      )}
    </Drawer>
  </>);

  return (wrapContainer ?
      <PageContainer>
        <AlarmRuleTale/>
      </PageContainer>
      : <AlarmRuleTale/>
  );
}


export default AlarmRule;
